import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getDepartments, getDepartment, createDepartment, updateDepartment, deleteDepartment } from '../api/department'

// 异步获取部门列表
export const fetchDepartments = createAsyncThunk(
  'department/fetchDepartments',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getDepartments(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取部门列表失败' })
    }
  }
)

// 异步获取部门详情
export const fetchDepartmentDetail = createAsyncThunk(
  'department/fetchDepartmentDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getDepartment(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取部门详情失败' })
    }
  }
)

// 异步创建部门
export const addDepartment = createAsyncThunk(
  'department/addDepartment',
  async (departmentData, { rejectWithValue }) => {
    try {
      const response = await createDepartment(departmentData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加部门失败' })
    }
  }
)

// 异步更新部门
export const editDepartment = createAsyncThunk(
  'department/editDepartment',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateDepartment(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新部门失败' })
    }
  }
)

// 异步删除部门
export const removeDepartment = createAsyncThunk(
  'department/removeDepartment',
  async (id, { rejectWithValue }) => {
    try {
      await deleteDepartment(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除部门失败' })
    }
  }
)

const initialState = {
  departments: [],
  departmentTree: [],
  currentDepartment: null,
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  loading: false,
  error: null
}

// 构建部门树形结构
const buildDepartmentTree = (departments) => {
  // 找出所有根部门（parent_id为0的部门）
  const rootDepartments = departments.filter(dept => dept.parent_id === 0)

  // 递归构建树形结构
  const buildTree = (parentId) => {
    const children = departments.filter(dept => dept.parent_id === parentId)
    if (children.length === 0) return []

    return children.map(child => ({
      key: child.id,
      title: child.name,
      children: buildTree(child.id)
    }))
  }

  return rootDepartments.map(root => ({
    key: root.id,
    title: root.name,
    children: buildTree(root.id)
  }))
}

const departmentSlice = createSlice({
  name: 'department',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    setCurrentPage: (state, action) => {
      state.pagination.current = action.payload
    },
    setPageSize: (state, action) => {
      state.pagination.pageSize = action.payload
    },
    clearCurrentDepartment: (state) => {
      state.currentDepartment = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取部门列表
      .addCase(fetchDepartments.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchDepartments.fulfilled, (state, action) => {
        state.loading = false
        state.departments = action.payload.data || []
        state.departmentTree = buildDepartmentTree(action.payload.data || [])
        state.pagination.total = action.payload.total || 0
      })
      .addCase(fetchDepartments.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取部门列表失败'
      })
      // 获取部门详情
      .addCase(fetchDepartmentDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchDepartmentDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentDepartment = action.payload
      })
      .addCase(fetchDepartmentDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取部门详情失败'
      })
      // 添加部门
      .addCase(addDepartment.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addDepartment.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addDepartment.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加部门失败'
      })
      // 更新部门
      .addCase(editDepartment.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editDepartment.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editDepartment.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新部门失败'
      })
      // 删除部门
      .addCase(removeDepartment.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeDepartment.fulfilled, (state, action) => {
        state.loading = false
        state.departments = state.departments.filter(department => department.id !== action.payload)
        // 重新构建部门树
        state.departmentTree = buildDepartmentTree(state.departments)
      })
      .addCase(removeDepartment.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除部门失败'
      })
  }
})

export const { clearError, setCurrentPage, setPageSize, clearCurrentDepartment } = departmentSlice.actions
export default departmentSlice.reducer